/**
 * 登录
 */
import dayjs from "dayjs";
import { getUserInfo } from "../../../model/service/account/userInfo";
import codeUtil from "../../../util/code/codeUtil";
import { decrypt, hashPassword } from "../../../util/security";
import { getToken } from "../../../util/token";

// 登录方式
export enum LOGIN_TYPE {
  PASS_LOGIN = "1",
  PHONE_LOGIN = "2",
  AUTO_LOGIN = '3',
}

export interface IUserKey {
  expires: dayjs.Dayjs;
  userId: string;
}

export default async function login(ctx: Context, next: Next): Promise<void> {
  const {
    body: { type, data },
  } = ctx.request;
  const { username, password, phoneNumber, code, userKey } = data;

  let result = {} as IAnyObject;

  // 查询用户
  if (type === LOGIN_TYPE.PASS_LOGIN) {
    result = await getUserInfo({ username, password: hashPassword(password) });
  } else if (type === LOGIN_TYPE.PHONE_LOGIN) {
    if (!codeUtil.verifyCode(phoneNumber, code)) {
      ctx.api.fail(-1, "验证码错误");
      return next();
    }
    result = await getUserInfo({ phoneNumber });
  } else {
    const { expires, userId } = JSON.parse(decrypt(userKey));

    // cookie过期
    if (dayjs(expires).isBefore(dayjs())) {
      ctx.api.fail(-1, "userKey已过期");
      return next();
    }
    result = await getUserInfo({ uid: userId });
  }

  // 登录之后返回token
  const token = getToken({ uid: result.uid, username: result.username });
  ctx.res.setHeader("Authorization", token);
  //解决跨域导致前端获取不到token的问题
  ctx.res.setHeader("Access-Control-Expose-Headers", "Authorization");

  if (result.length) {
    ctx.api.success(result[0], "sucess");
  } else {
    ctx.api.fail(
      -1,
      `${
        type === LOGIN_TYPE.PASS_LOGIN ? "用户名或者密码错误" : "手机号不正确"
      }`
    );
  }

  return next();
}
